package com.cari.oa.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cari.oa.domain.SysOperLogEntity;
import com.cari.oa.manage.SpringContextHolder;
import com.cari.oa.service.SysOperLogService;
import com.cari.oa.util.Contants;
import com.cari.oa.util.DateUtils;

/**
 * 系统操作日志controller
 * User: yexuhui
 * Date: 2012-12-28
 * Time: 上午11:42:51
 */
@Controller
public class SysOperLogController {

	@Resource
	private SysOperLogService sysOperLogService;
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(df, true));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
	}
	
    @RequestMapping("/system/operlog/list.do")
    public String list(String userName, String moduleName, Date starttime, Date endtime, Integer curPage, ModelMap modelMap) {
        if(curPage == null) curPage = 1;
        long totalRecords = sysOperLogService.getCount(userName, moduleName, starttime, endtime);
        long totalPage = totalRecords / Contants.PAGE_SIZE + (totalRecords % Contants.PAGE_SIZE != 0 ? 1 : 0);
        List<SysOperLogEntity> logList = sysOperLogService.getPage(userName, moduleName, starttime, endtime, curPage, Contants.PAGE_SIZE);

        modelMap.addAttribute("logList", logList);
        modelMap.addAttribute("curPage", curPage);
        modelMap.addAttribute("totalPage", totalPage);
        modelMap.addAttribute("totalRecords", totalRecords);

        modelMap.addAttribute("userName", userName);
        modelMap.addAttribute("moduleName", moduleName);
        modelMap.addAttribute("starttime", DateUtils.date2Str(starttime, DateUtils.NORMAL_FORMAT));
        modelMap.addAttribute("endtime", DateUtils.date2Str(endtime, DateUtils.NORMAL_FORMAT));

        return "system/operlog/list";
    }
    
    public static void addOperLog(String username, String moduleName, String description) {
    	SysOperLogEntity logEntity = new SysOperLogEntity();
    	logEntity.setUserName(username);
    	logEntity.setModuleName(moduleName);
    	logEntity.setDescription(description);
    	
    	try {
			SysOperLogService logService = SpringContextHolder.getBean(SysOperLogService.class);
			logService.insert(logEntity);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}
